﻿/***************************************************************************************/
//创建者：  江名峰
//时间：    2011-06-09
//说明：    
//封装素材管理控制器的辅助功能
//更新日志：2011-09-13，移动到新的项目HU8.Helpers.Files
//
/***************************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Ionic.Zip;
using HU8.Helpers.Files.Resource;
using HU8.Helpers.Base;

namespace HU8.Helpers.Files
{
    /// <summary>
    /// 表示素材管理控制器的帮助类
    /// </summary>
    public class ResourceHelper
    {
        /// <summary>
        /// 文件类型后辍字典.   chiron  2011-7-8
        /// </summary>
        private readonly static IDictionary<string, string[]> fileTypeExtension = new Dictionary<string, string[]>
        {
            {"image",new string[]{".png",".jpg","jpeg",".bmp",".gif"}},
            {"flash",new string[]{".swf"}},
            {"compressed",new string[]{".rar",".zip",".gz"}}
        };

        #region validation

        /// <summary>
        /// 测试文件夹名是否合法
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool ValidateDirectoryName(string name)
        {
            return name.IndexOfAny(Path.GetInvalidPathChars()) == -1;
        }

        /// <summary>
        /// 测试文件名是否合法
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool ValidateFileName(string name)
        {
            return name.IndexOfAny(Path.GetInvalidFileNameChars()) == -1;
        }

        /// <summary>
        /// 测试文件夹权限
        /// </summary>
        /// <param name="path"></param>
        /// <param name="read"></param>
        /// <param name="write"></param>
        /// <param name="delete"></param>
        /// <returns></returns>
        public bool ValidateFolderPermission(string path, bool read, bool write, bool delete)
        {
            return true;
        }

        #endregion

        #region creation
        /// <summary>
        /// 创建新的文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <param name="folderName"></param>
        /// <returns></returns>
        public static JsonResponse CreateFolder(string path, string folderName)
        {
            return FileHelper.CreateFolder(path, folderName);
        }

        /// <summary>
        /// 创建新文本文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static JsonResponse CreateTextFile(string path, string fileName, bool overwrite, string preset = "")
        {
            return FileHelper.CreateTextFile(path, fileName, overwrite, preset);
        }

        #endregion

        #region zip
        /// <summary>
        /// 压缩指定文件集合
        /// </summary>
        /// <param name="files"></param>
        /// <param name="saveTo"></param>
        public static void GenerateZipFile(List<string> files, string saveTo, string comment)
        {
            ZipHelper.GenerateZipFile(files, saveTo, comment);
        }
        
        /// <summary>
        /// 解压文件夹
        /// 解压的时候，结构是否也在？
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="unzipTo">解压到</param>
        /// <param name="overwrite">是否覆盖</param>
        public static void UnzipFile(string file, string unzipTo, bool overwrite)
        {
            ZipHelper.UnzipFile(file, unzipTo, overwrite);
        }

        /// <summary>
        /// 获得ZIP的信息，包括结构信息
        /// </summary>
        /// <param name="file">文件路径</param>
        /// <param name="showHeader">显示ZIP的头部信息</param>
        /// <returns></returns>
        public static string GetZipInfo(string file)
        {
            return ZipHelper.GetZipInfo(file);
        }
        #endregion

        #region getters
        /// <summary>
        /// 获取文件夹的大小
        /// </summary>
        /// <param name="p">路径</param>
        /// <returns></returns>
        public static long GetDirectorySize(string p)
        {
            try
            {
                // Calculate total bytes of all files in a loop.
                long b = 0;

                // Get array of all file names.
                string[] paths = Directory.GetDirectories(p, "*.*");
                foreach (string path in paths)
                {
                    b += GetDirectorySize(path);
                }

                string[] a = Directory.GetFiles(p, "*.*");
                foreach (string name in a)
                {
                    FileInfo info = new FileInfo(name);
                    b += info.Length;
                }
                // 4
                // Return total size
                return b;
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 获取文件夹列表
        /// </summary>
        /// <param name="currentDir">当前文件夹</param>
        /// <param name="physicalPath">物理文件夹，用来计算相对路径</param>
        /// <param name="basePath">基础相对路径，用来计算路径</param>
        /// <returns></returns>
        public static List<Folder> GetFolderList(DirectoryInfo currentDir, string physicalPath, string basePath)
        {
            List<Folder> folders = new List<Folder>();
            if (currentDir != null)
            {
                DirectoryInfo[] dirs = currentDir.GetDirectories();
                foreach (DirectoryInfo info in dirs)
                {
                    Folder folder = new Folder();
                    folder.Name = info.Name;
                    folder.FileCount = info.GetFiles().Length;
                    folder.FolderCount = info.GetDirectories().Length;
                    folder.Path = basePath + info.FullName.Replace(physicalPath, "").Replace("\\", "/"); ;
                    folder.LastModified = info.LastWriteTime;
                    folder.Created = info.CreationTime;
                    folders.Add(folder);
                }
            }
            return folders;
        }

        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="dir">当前文件夹</param>
        /// <returns></returns>
        /// chiron  changed 2011-7-8
        public static List<FolderFile> GetFileList(DirectoryInfo dir, string fullPath, string type)
        {
            FileInfo[] fileInfos = dir.GetFiles();
            List<FolderFile> files = new List<FolderFile>();

            if (fileTypeExtension.Keys.Contains(type))
            {
                var fileExt = fileTypeExtension[type];
                foreach (FileInfo ff in fileInfos)
                {
                    FolderFile f = new FolderFile();
                    f.Name = ff.Name;
                    f.Path = fullPath + "/" + ff.Name;
                    f.Size = ff.Length;
                    f.Extension = ff.Extension;
                    f.LastModified = ff.LastWriteTime;
                    f.Created = ff.CreationTime;
                    if (fileExt.Contains(f.Extension))
                    {
                        files.Add(f);
                    }
                }
            }
            else
            {
                foreach (FileInfo ff in fileInfos)
                {
                    FolderFile f = new FolderFile();
                    f.Name = ff.Name;
                    f.Path = fullPath + "/" + ff.Name;
                    f.Size = ff.Length;
                    f.Extension = ff.Extension;
                    f.LastModified = ff.LastWriteTime;
                    f.Created = ff.CreationTime;
                    files.Add(f);
                }
            }

            /*
            foreach (FileInfo ff in fileInfos)
            {
                FolderFile f = new FolderFile();
                f.Name = ff.Name;
                f.Path = fullPath + "/" + ff.Name;
                f.Size = ff.Length;
                f.Extension = ff.Extension;
                f.LastModified = ff.LastWriteTime;
                f.Created = ff.CreationTime;
                if (string.IsNullOrEmpty(type))
                {
                    files.Add(f);
                }
                else if (type == "image")
                {
                    if (f.Extension == ".png" || f.Extension == ".jpg" || f.Extension == ".jpeg" || f.Extension == ".bmp" || f.Extension == ".gif")
                    {
                        files.Add(f);
                    }
                }
                else if (type == "flash")
                {
                    if (f.Extension == ".swf")
                    {
                        files.Add(f);
                    }
                }
            }
            */
            return files;
        }
        #endregion

        #region operation
        /// <summary>
        /// 将文件/文件夹拷贝或移动到某一个地方
        /// </summary>
        /// <param name="physicalPath">源文件、文件夹物理路径</param>
        /// <param name="toFolder">目标文件夹 物理路径路径</param>
        /// <param name="isFile">是否为文件</param>
        /// <param name="isMove">是否移动</param>
        public static JsonResponse Relocate(List<string> fileList, string toFolder, bool isMove)
        {
            return FileHelper.Relocate(fileList, toFolder, isMove);
        }

        

        /// <summary>
        /// 重命名文件或文件夹
        /// </summary>
        /// <param name="serverPath">物理地址</param>
        /// <param name="name">新的名称，没有后缀</param>
        /// <returns></returns>
        public static JsonResponse Rename(string serverPath, string name)
        {
            return FileHelper.Rename(serverPath, name);
        }

        #endregion


    }
}